package com.tools.gensql.model;

import lombok.Data;

import java.io.Serializable;
import java.util.concurrent.Callable;

@Data
public class R<T> implements Serializable {
    private int code;
    private String msg;
    private T data;

    public R() {
    }

    public R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> R<T> ok(T data) {
        return new R<>(0, "success", data);
    }

    public static <T> R<T> error(int code, String msg)  {
        return new R<>(code, msg);
    }

    public static <T> R<T> error(String msg)  {
        return new R<>(500, msg);
    }

    public static <T> R<T> from(Runnable runnable) {
        try {
            runnable.run();
            return ok(null);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    public static <T> R<T> from(Callable<T> callable)  {
        try {
            return ok(callable.call());
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }
}
